package fun.codedesign.jdk.util.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-02 11:12
 * @since 1.0.0
 */
public class IOStringCount {

    public static void main(String[] args) throws IOException {
        String file = "basic/file.txt";
        FileInputStream fis = new FileInputStream(file);
        try(InputStreamReader isr = new InputStreamReader(fis)) {
            int i;
            char x;
            Map<Character, Integer> map = new HashMap<>();
            int count = 1;
            while ((i = isr.read()) != -1) {
                x = (char) i;
                //System.out.println(x);
                if (!map.containsKey(x)) {
                    map.put(x, 1);
                }
                if (map.containsKey(x)) {
                    count += 1;
                    map.put(x, count);
                }
            }
            //System.out.println(map);

            Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
            //System.out.println(entrySet);
            ArrayList<Map.Entry<Character, Integer>> list = new ArrayList<Map.Entry<Character, Integer>>(entrySet);
            Collections.sort(list, new ByValue2());
            for (Map.Entry<Character, Integer> entry : list) {
                char key = entry.getKey();
                int value = entry.getValue();
                DecimalFormat df = new DecimalFormat("0.##%");
                System.out.println(key + "\t" + value + "\t" + df.format((double) value / (list.size())));
            }
        }
    }
}

class ByValue2 implements Comparator<Map.Entry<Character, Integer>> {
    public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
        return o2.getValue() - o1.getValue();
    }
}
